<template>
	<view class="content" style="flex-direction: column;height: 100vh;justify-content: space-between;">
		<view class="header" style="flex:1;background: #eee;overflow: scroll;">
			<!-- <js-error mode="top" ref="jsError" z-index="999"></js-error> -->
			<!-- 轮播图 -->
			<swiper v-if="picLunboList.length" class="swiper-box" :indicator-dots="indicatorDots" :autoplay="autoplay" :interval="interval"
				indicator-active-color="#ffffff" :duration="duration">
				<swiper-item v-for="(item, index) in picLunboList" :key="index" @click="clickImg(item,'1')">
					<view class="swiper-item">
						<!--  mode="aspectFill"  -->
						<image class="image" :src="baseUrl + item.picUrl"/>
					</view>
				</swiper-item>
			</swiper>

			<view style="background: #eee;padding: 10px;">
				<!-- 套餐信息组件 -->
				<package-info :package-data="spData" />

				<!-- 物料系列组件 -->
				<material-series
					v-if="mainList && mainList.length > 0"
					title="物料系列-主产品"
					:list="mainList"
					:base-url="baseUrl"
					@product-click="onProductClick"
					@quantity-change="onQuantityChange"
					@item-select="onItemSelect"
				/>

				<material-series
					v-if="czpList && czpList.length > 0"
					title="物料系列-次主品"
					:list="czpList"
					:base-url="baseUrl"
					@product-click="onProductClick"
					@quantity-change="onQuantityChange"
					@item-select="onItemSelect"
				/>

				<material-series
					v-if="fpList && fpList.length > 0"
					title="物料系列-辅品"
					:list="fpList"
					:base-url="baseUrl"
					@product-click="onProductClick"
					@quantity-change="onQuantityChange"
					@item-select="onItemSelect"
				/>

				<material-series
					v-if="wlList && wlList.length > 0"
					title="物料系列-物料"
					:list="wlList"
					:base-url="baseUrl"
					@product-click="onProductClick"
					@quantity-change="onQuantityChange"
					@item-select="onItemSelect"
				/>
			</view>
		</view>

		<view class="navigation">
			<view class="left">
				<view class="item car" @click="jumpCart">
					<u-badge class="car-num" :count="vuex_cartList" type="error" :offset="[-3, -6]"></u-badge>
					<u-icon name="shopping-cart" :size="40" :color="$u.color['contentColor']"></u-icon>
					<view class="text u-line-1">购物车</view>
				</view>
				<view class="item">
					<view style="font-size: 14px;color: red;">
						合计：￥{{cartTotalPrice}}
					</view>
					<view style="font-size: 14px;">
						总数量：{{cartTotalNum}}
					</view>
				
				</view>
			</view>
			<view class="right">
				<view class=" cart btn u-line-1" @click="butClick">{{ carButton }}</view>
			</view>



		</view>
		<u-popup v-model="show" mode="bottom" closeable>
			<view style="background-color: #fff;padding: 10px">
				<view style="font-weight: bold;font-size: 16px;margin-bottom: 10px;">{{spData.title}}</view>
				<view style="display: flex;justify-content: space-between;">
					<!-- <view style="color: #aaa;">规格:{{spData.cinvstd?spData.cinvstd:''}}</view> -->
					<view style="background:  bisque ;font-size: 14px;padding: 3px;color: #ff874b;border-radius: 5px">
						1{{spData.appUnitName}}起订</view>
				</view>
				<view style="display: flex;justify-content: space-between;margin-top: 10px;">
					<view class="">
						<text style="color: red;font-size: 20px;">￥{{ spData.fmaount?spData.fmaount:'暂无单价' }}</text>
						<text>/{{spData.appUnitName}}</text>
					</view>
					<u-number-box v-if="spData.batchType != 1" input-width="120" input-height="60" v-model="spData.count" :min='1' @change="valChange"></u-number-box>
				</view>
				<view
					style="color: red;text-align: right;border-top:1px solid #aaa ;border-bottom:1px solid #aaa ;padding: 10px;margin: 10px 0;">
					合计：
					<text style="font-size: 20px;">￥{{sumPrice}}</text>
				</view>
				<view style="text-align: right;padding: 10px 0;">
					<text @click="submit"
						style="padding: 10px;background: #00aa00;color: #fff;border-radius: 5px">{{buttext}}</text>
				</view>
			</view>
		</u-popup>
	</view>

</template>

<script>
	import {
			mapState
		} from 'vuex';
	import MaterialSeries from '@/components/material-series/material-series.vue';
	import PackageInfo from '@/components/package-info/package-info.vue';

	export default {
		components: {
			MaterialSeries,
			PackageInfo
		},
		data() {
			return {
				buttext: '确定',
				carButton: '加入购物车',
				value: 1,
				show: false,
				indicatorDots: true,
				autoplay: true,
				interval: 2000, //切换的间隔时间
				duration: 500, //滑动动画时长
				spData: {},
				salesRefList: [{
					salesId:'',
					salesDid:'',
					invCode:'',
					iqty:''
				}],
				sumPrice: 0,
				picDetailList:[],
				picLunboList:[
					{
						picUrl: '/static/image/orderBg.jpg'
					}
				],
				baseUrl:'',
				listArr:[],
				isNewCart:false,
                // 是否为购物车编辑模式
                isEditCart: false,
                // 当前编辑的购物车条目ID
                currentCartId: '',
                // wlList:[],
                // czpList:[],
                // fpList:[],
                // mainList:[],
                wlList: [
					{
						selected: false
					},
				],
                mainList: [
					{
						selected: false
					},
				],
                fpList: [
					{
						selected: false
					}
				],
                czpList: [
                    {
                        selected: false,
                    }
                ],
                // 全局防重复提交标记
                isSubmitted: false,
				ope: 0 ,//操作类型 0 新增 1 修改
            }
        },
		computed: {
			...mapState(['vuex_cartList']),
			// 购物车商品总价
			cartTotalPrice() {
				console.log(this.listArr, 'this.listArr==');
				// 计算list列表中所有选中商品的价格
				var sum = 0
				this.listArr.forEach(el => {
					sum = el.sumPrice  + sum
				})
				return sum
			},
			// 购物车件数
			cartTotalNum() {
				// 计算list列表中所有选中商品的价格
				var num = 0
				this.listArr.forEach(el => {
					num = num + el.iqty;
				})
				return num
			},
		},
		async onLoad(params) {
			
			this.baseUrl = this.vuex_config.baseUrl
			// this.spData = JSON.parse(params.item)

			if(params.cartId){
				// 标记为购物车编辑模式，并记录当前购物车ID
				this.isEditCart = true;
				this.ope = 1;
				this.currentCartId = params.cartId;
				uni.setNavigationBarTitle({
					title: '购物车修改',
				});
				this.carButton = '确定修改';
				await this.$u.api.shop.shopSalesData({
					id:params.cartId,
				}).then(res => {
					// console.log(res,'res==');
					// // this.listArr = res.basInv || []
					this.picLunboList = [{
						picUrl: res.shopSalesPackage.picUrl
					}]
					// 初始化数据并添加 selected 字段
					this.wlList = this.initializeSelectedField(res.shopSalesPackage.wlList || [])
					this.mainList = this.initializeSelectedField(res.shopSalesPackage.mainList || [])
					this.fpList = this.initializeSelectedField(res.shopSalesPackage.fpList || [])
					this.czpList = this.initializeSelectedField(res.shopSalesPackage.czpList || [])
					this.spData = res.shopSalesPackage
					this.spData.appPrice = this.spData.fmaount?this.spData.fmaount:'暂无单价'
					this.spData.count = 1
					this.sumPrice = this.spData.appPrice * 1
					console.log(res,'res=======', this.mainList);

					// 编辑模式下，按钮文案与行为调整
					this.buttext = '立即购买';

					// 数据加载完成后，更新 salesRefList
					this.$nextTick(() => {
						this.updateSalesRefList();
					});
				})
			} else {
				
				uni.setNavigationBarTitle({
					title: '购物车详情',
				});
				let data = JSON.parse(params.data)
				console.log(data,'data=======');
				this.isNewCart = data.isNewCart
				await this.$u.api.shop.salesData({id:data.busKey})
					.then(res => {
						this.picLunboList = [{
							picUrl: res.picUrl
						}]
						// 初始化数据并添加 selected 字段
						this.wlList = this.initializeSelectedField(res.wlList || [])
						this.mainList = this.initializeSelectedField(res.mainList || [])
						this.fpList = this.initializeSelectedField(res.fpList || [])
						this.czpList = this.initializeSelectedField(res.czpList || [])
						this.spData = res
						this.spData.appPrice = data.fprice?data.fprice:'暂无单价'
						this.spData.count = data.iqty ? data.iqty : 1
						// this.sumPrice = this.spData.appPrice * 1
						this.sumPrice = this.spData.count * data.fprice
						console.log(res,'res=======', this.mainList);

						// 数据加载完成后，更新 salesRefList
						this.$nextTick(() => {
							this.updateSalesRefList();
						});
					});

			}

			await this.listData();



			
			// console.log(this.spData.count, 'this.spData.count==');
		},
		methods: {
			// 初始化 selected 字段
			initializeSelectedField(list) {
				return list.map(item => {
					// 如果 groupType 为 '0'，默认选中
					return {
						...item,
						selected: item.groupType == '0' || item.groupType == '' || item.groupType == undefined || item.falgCHeck == '1',
						quantity: item.quantity || ''
					}
				})
			},
			// 组件事件处理方法
			onProductClick(item) {
				console.log('产品点击:', item);
				// 可以在这里处理产品点击事件，比如显示产品详情
			},
			onQuantityChange(data) {
				console.log('数量变化:', data);
				// 处理数量变化
			},
			onItemSelect(data) {
				console.log('选择状态变化:', data);

				// 手动更新父组件中对应的 item 的 selected 状态
				this.updateItemSelectedState(data.item, data.selected);

				// 处理选择状态变化
				this.updateCartInfo();
				this.updateSalesRefList();
			},
			updateItemSelectedState(targetItem, selected) {
				// 在所有列表中找到对应的 item 并更新其 selected 状态
				const allLists = [
					{ list: this.mainList, name: 'mainList' },
					{ list: this.czpList, name: 'czpList' },
					{ list: this.fpList, name: 'fpList' },
					{ list: this.wlList, name: 'wlList' }
				];
				console.log('更新列表:', targetItem);
				allLists.forEach(({ list, name }) => {
					const index = list.findIndex(item => {
						// 通过多个字段来匹配，确保找到正确的 item
						console.log('targetItem:', targetItem.id, item.id,item);
						return item.id === targetItem.id
					});

					if (index !== -1) {
						console.log(`在 ${name} 中找到匹配项，索引: ${index}, 更新 selected 为: ${selected}`);
						this.$set(list[index], 'selected', selected);
					}
				});
			},
			updateCartInfo() {
				// 更新购物车信息
				let selectedItems = [];
				[...this.mainList, ...this.czpList, ...this.fpList, ...this.wlList].forEach(item => {
					if (item.selected) {
						selectedItems.push(item);
					}
				});
				console.log('已选择的商品:', selectedItems);
			},
			updateSalesRefList() {
				// 组装勾选的数据到 salesRefList 数组
				this.salesRefList = [];

				// 遍历所有列表，找出已选中的商品
				const allItems = [...this.mainList, ...this.czpList, ...this.fpList, ...this.wlList];
				console.log('所有商品数量:', allItems.length);

				allItems.forEach((item, index) => {
					console.log(`商品 ${index}:`, {
						id: item.id,
						selected: item.selected,
						groupType: item.groupType,
						name: item.basInv ? item.basInv.cinvname : 'unknown'
					});

					if (item.selected) {
						const salesRefItem = {
							salesId: this.spData.id || '',
							salesDid: item.id || '',
							invCode: item.basInv ? item.basInv.cinvcode : '',
							iqty: item.iqty || ''
						};
						this.salesRefList.push(salesRefItem);
						console.log('添加到 salesRefList:', salesRefItem);
					}
				});

				console.log('更新后的 salesRefList 长度:', this.salesRefList.length);
				console.log('更新后的 salesRefList:', this.salesRefList);
			},
			butClick(){
				// 先验证套餐包勾选规则
				this.validatePackageSelection();
			},

			// 验证套餐包勾选规则
			validatePackageSelection() {
				// 构建API参数
				const params = {
					cusCode: this.vuex_basCus.code,
					id: this.spData.id,
					czpList: this.buildGroupSelectionList(this.czpList),
					mainList: this.buildGroupSelectionList(this.mainList),
					wlList: this.buildGroupSelectionList(this.wlList),
					fpList: this.buildGroupSelectionList(this.fpList)
				};
				// 显示构建的参数信息（调试用）
				this.showParameterInfo(params);

				// 调用验证API
				this.$u.api.shop.selPackage(params)
					.then(res => {
						console.log('selPackage API 响应:', res);
						if (res.result === 'true' || res.success === true) {
							// 验证通过，根据是否为购物车编辑模式走不同逻辑
							if (this.isEditCart && this.currentCartId) {
								this.submit();
							} else {
								this.proceedToCart();
							}
						} else {
							// 验证失败，显示错误信息
							uni.showModal({
								title: '验证失败',
								content: res.message || '套餐包勾选规则验证失败',
								showCancel: false
							});
						}
					})
					.catch(error => {
						uni.showModal({
							title: '网络错误',
							content: '验证套餐包勾选规则时发生错误，请检查网络连接',
							showCancel: false
						});
					});
			},

			// 显示参数信息（调试用）
			showParameterInfo(params) {
				let info = `API参数构建完成:\n`;
				info += `客户代码: ${params.cusCode}\n`;
				info += `套餐ID: ${params.id}\n`;
				info += `主产品: ${params.mainList.length} 个分组\n`;
				info += `次主品: ${params.czpList.length} 个分组\n`;
				info += `辅品: ${params.fpList.length} 个分组\n`;
				info += `物料: ${params.wlList.length} 个分组\n`;

				console.log(info);

				// 可以选择性地显示给用户（调试时使用）
				// uni.showModal({
				// 	title: '参数信息',
				// 	content: info,
				// 	showCancel: false
				// });
			},

			// 构建分组选择列表
			buildGroupSelectionList(list) {
				if (!list || list.length === 0) {
					console.log('列表为空，返回空数组');
					return [];
				}

				console.log('构建分组选择列表，输入列表:', list);

				// 按groupId分组
				const groupMap = {};
				list.forEach(item => {
					console.log('处理商品:', {
						id: item.id,
						groupId: item.groupId,
						selected: item.selected,
						name: item.basInv ? item.basInv.cinvname : 'unknown'
					});

					if (item.selected) {
						const groupId = item.groupId || 'default';
						if (!groupMap[groupId]) {
							groupMap[groupId] = [];
						}
						groupMap[groupId].push(item.id);
						console.log(`添加商品ID ${item.id} 到分组 ${groupId}`);
					}
				});

				console.log('分组映射:', groupMap);

				// 转换为API需要的格式
				const result = [];
				for (const groupId in groupMap) {
					const groupData = {
						groupId: groupId,
						selIds: groupMap[groupId].join(',')
					};
					result.push(groupData);
					console.log('添加分组数据:', groupData);
				}

				console.log('最终构建结果:', result);
				return result;
			},

			// 验证通过后继续原有的加入购物车逻辑
			proceedToCart() {
				if(this.spData.fmaount == '暂无单价'){
					this.$u.toast('暂无单价，无法加入购物车');
				}else{
					this.buttext='加入购物车';
                    this.spData.appUnitName = '套'
					this.show = true;
				}
			},
			clickImg(item,flag) {
				let arr = []
				if(flag == '1'){
					arr = [...this.picLunboList]
				}else if(flag == '2'){
					arr = [...this.picDetailList]
				}
				let urls = arr.map(val => {
					return (this.baseUrl +  val.picUrl)
				})
				uni.previewImage({
					urls, //需要预览的图片http链接列表，多张的时候，url直接写在后面就行了
					current: this.baseUrl + item.picUrl, // 当前显示图片的http链接，默认是第一个
					success: function(res) {},
					fail: function(res) {},
					complete: function(res) {},
				})
			},
			jumpCart() {
				// uni.reLaunch({
				// 	url: '/pages/btdm/index/cart/cart',
				// })
				uni.switchTab({
				  url: '/pages/btdm/index/cart/cart'
				})
				
			},
			valChange(e) {
				console.log('当前值为: ' + e.value)
				this.sumPrice = this.spData.appPrice * e.value
				console.log('this.spData.count: ' + this.spData.count)
			},
			async listData(){
				await this.$u.api.shop.cartListData({
					cusCode:this.vuex_basCus.code,
					createBy:this.vuex_user.userCode,
				})
				.then(res => {
						let arr = []
						for (let key in res) {
							res[key].forEach(item=>{
									if(item.busType == '0'){
										item.sumPrice = item.iqty * (item.shopInv.basInv.appPrice?item.shopInv.basInv.appPrice:'暂无单价')
									}else if(item.busType == '1'){
										item.sumPrice = item.iqty * (item.shopProductSell.fprice?item.shopProductSell.fprice:'暂无单价')
									}else if(item.busType == '3'){
										item.sumPrice = item.iqty * (item.fprice?item.fprice:'暂无单价')
									}
									arr.push(item)
							})
						}
						this.listArr = arr
				});
			},
            async submit() {
                let that = this
                console.log(this.spData,'spData====');
                // 防重复提交：正在提交则直接返回
                if (this.isSubmitted) {
                    this.$u.toast('正在提交，请勿重复操作');
                    return;
                }
                this.isSubmitted = true;
                try {
                     // 原有加入购物车逻辑
					if(this.vuex_basCus.code && this.vuex_basCus.code != '00'){
						let data = {
							cusCode:this.vuex_basCus.code,
							busType:'3',
							busKey:this.spData.id,
							iqty:this.spData.count,
							fprice:this.spData.appPrice?this.spData.appPrice:'暂无单价',
							appUnitCode:this.spData.appUnitCode,
							salesRefList:this.salesRefList, 
							ope: this.ope,
						}
						if(data.fprice != '暂无单价'){
							const res = await this.$u.api.shop.addToCart(data);
							if(res.result == 'true'){
								this.show = false;
								// 如果修改则提示修改成功
								if (this.isEditCart) {
									setTimeout(()=>{
										that.$u.toast('修改成功');
									},500)
									setTimeout(()=>{
										that.jumpCart()
									},1000)
									// 调转路由 pages/btdm/index/cart/cart
									
								} else {								
									setTimeout(()=>{
										that.$u.toast(res.message);
									},500)
									// 仅在非编辑模式下执行原 561-571 行逻辑
									if (this.isNewCart) {
										const tempCartData = {
											sumPrice: this.sumPrice,
											iqty: this.spData.count,
										};
										this.listArr.push(tempCartData);
									}
									this.$store.commit("modifyCartList", this.listArr.length);
								}
								this.isNewCart = false
								await this.listData()
							}else{
								uni.showModal({
									title: '提示',
									content: res.message,
									showCancel: false,
									success: function(res) {}
								});
							}
						}else{
							this.$u.toast('暂无单价，无法加入购物车');
						}
					}else{
						this.$u.toast('请先选择门店');
					}
                } catch (error) {
                    console.log(error,'error=========');
                    this.$u.toast('提交失败，请稍后重试');
                } finally {
                    this.isSubmitted = false;
                }
            }
        },


	}
</script>

<style lang="scss" scoped>
	page {
		width: 100%;
		height: 98%;
		text-align: center;
		overflow: scroll;
	}
	/deep/ .u-icon-plus{
	    width: 120rpx !important;
	}
	/deep/ .u-icon-minus {
	    width: 120rpx !important;
	}

	.content {
		/* text-align: center; */
		display: flex;
		flex-direction: column;
	}

	.swiper-box {
		/* object-fit: full; */
		height: 220px;
	}

	.swiper-box2 {
		/* object-fit: full; */
		/* height: 190px; */
		/* max-width:100%; */
		height: 150px;
	}

	.swiper-box3 {
		/* object-fit: full; */
		height: 146px;
		/* max-width: 100%;		 */
	}

	.swiper-item {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: column;
		justify-content: center;
		align-items: center;
		background-color: #fff;
		color: #fff;
	}

	.image {
		width: 750rpx;
		height: 220px;
		/* object-fit: cover; */
	}

	.image2 {
		width: 750rpx;
		height: 150px;
		/* object-fit: cover; */
		/* object-fit: contain; */
	}

	.image3 {
		/* width: 750rpx;
		height: 1400upx; */
		/* position: fixed;
		object-fit: contain; */
		width: 750rpx;
		height: 146px;
	}

	.action {
		/* position: fixed;
			top:100px;
			z-index: 9999; */
	}

	.warp {
		color: #000000;
	}

	.leftLine {
		width: 80px;
		height: 1px;
		background: linear-gradient(244deg, rgba(26, 26, 26, 1.0) 50%, rgba(255, 255, 255, 0) 100%);
	}

	.rightLine {
		width: 80px;
		height: 1px;
		background: linear-gradient(244deg, rgba(255, 255, 255, 0) 0%, rgba(26, 26, 26, 1.0) 50%);
	}

	.tag {
		margin-left: 4%;
	}

	.tag1 {
		margin-left: 5%;
	}

	.navigation {
		width: 100%;
		/* position: fixed;
		bottom: 96rpx;
		z-index: 111; */
		display: flex;
		justify-content: space-between;
		// margin-top: 100rpx;
		border: solid 1rpx #eee;
		background-color: #ffffff;
		padding: 16rpx;


		.left {
			display: flex;
			font-size: 20rpx;

			.item {
				margin: 0 30rpx;

				&.car {
					text-align: center;
					position: relative;

					.car-num {
						position: absolute;
						top: -10rpx;
						right: -10rpx;
					}
				}
			}
		}

		.right {
			display: flex;
			font-size: 28rpx;
			align-items: center;

			.btn {
				line-height: 66rpx;
				padding: 0 30rpx;
				border-radius: 36rpx;
				color: #ffffff;
			}

			.cart {
				background-color: #ed3f14;
				margin-right: 30rpx;
			}

			.buy {
				background-color: #00aa00;
			}
		}
	}
</style>